import React, { useState } from 'react'
import style from './createPeriod.module.scss'
import { DatePicker, List } from 'antd'
import { IPeriod } from '../../../starter/model/interfaces'
import { v4 as uuidv4 } from 'uuid'
import PeriodItem from '../PeriodItem/PeriodItem'
import { useActions } from '../../../starter/hooks/actions'
import { useAppSelector } from '../../../starter/hooks/redux'
import dayjs, { Dayjs } from 'dayjs'
import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isBetween)

type TCreatePeriod = {
  onChange: ( period: IPeriod ) => void
  periods: IPeriod[],
  showRange: boolean
}

export default function CreatePeriod({onChange, periods, showRange}: TCreatePeriod) {
  const {setSelectedTmpPeriods} = useActions()
  const {period: tmpPeriod, selectedPeriods } = useAppSelector(state => state.tmp)
  const clickPeriodHandler = (period: IPeriod) => {
    const _period = selectedPeriods.find(item => item.id === period.id)

    if (_period) {
      setSelectedTmpPeriods(selectedPeriods.filter(item => item.id !== period.id))
    } else {
      setSelectedTmpPeriods([...selectedPeriods, period])
    }

  }
  const findIntersectionPeriods = (period: IPeriod) => {
    if (tmpPeriod && (
      dayjs(tmpPeriod?.startTime).isBetween(dayjs(period.startTime), dayjs(period.endTime)) ||
      dayjs(tmpPeriod?.endTime).isBetween(dayjs(period.startTime), dayjs(period.endTime)) ||
      dayjs(period.startTime).isBetween(dayjs(tmpPeriod?.startTime), dayjs(tmpPeriod?.endTime)) ||
      dayjs(period.endTime).isBetween(dayjs(tmpPeriod?.startTime), dayjs(tmpPeriod?.endTime))
    )) {
      return true
    } else {
      return false
    }
  }
  return (
    <div className={style.wrapper}>
      {
        showRange && <DatePicker.RangePicker
          value={tmpPeriod ? [dayjs(tmpPeriod.startTime), dayjs(tmpPeriod.endTime)] : null}
          onChange={(dates) => {
            if (dates && dates[0] && dates[1]) {
              onChange({id: uuidv4(), startTime: dates[0].toDate(), endTime:dates[1].toDate()})
            }
          }}
        />
      }
      {
        periods.length > 0 &&
        <List
          size="small"
          header={<div>Периоды уже занятые на этом проекте</div>}
          bordered
          dataSource={periods}
          style={{marginTop: '1rem'}}
          renderItem={(period) => <List.Item style={{background: findIntersectionPeriods(period) ? 'rgba(222,12,12,0.3)' : 'none'}} onClick={() => clickPeriodHandler(period)}>{<PeriodItem showCheckbox = {!showRange} period={period} isSelected={selectedPeriods.map(item => item.id).includes(period.id)}/>}</List.Item>}
        />
      }

    </div>
  )
}
